package cn.yunyichina.provider.framework.filter;

import java.util.Map;

import cn.yunyichina.provider.framework.utils.CallDataUtils;
import cn.yunyichina.provider.iface.entity.common.MethodArgs;
import cn.yunyichina.utils.security.Base64Method;

/**
 * dubbo入口数据过滤器
 * 
 * @author zhangkewen
 * 
 */
public class CallDataFilter {

    /**
     * 
     * @param data
     *            map数据
     * @param sessionflag
     *            0-无sessionid 1-有sessionid
     * @param signflag
     *            0-无须验证签名 1-需要验证签名信息
     * @param base64flag
     *            0-无须解密base64 1-需要解密base64
     * @return
     */
    public static MethodArgs filter(Map<String, String> data, int base64Flag) {

        MethodArgs methodArgs = new MethodArgs();
        try {
            String serviceName = "";
            String methodName = "";
            String serviceSecondName = "";
            String args = "";
            String method = data.containsKey("method") ? data.get("method") : "";
            String methodData = data.containsKey("data") ? data.get("data") : "";
            args = methodData;

            if (method == null || method.length() == 0) {
                methodArgs.setResultCode("3");
                methodArgs.setResultMessage("不存在method参数，或者参数长度为0!");
                return methodArgs;
            }

            // 解析method
            String[] methodToken = method.split("\\.");
            if (methodToken.length < 4) {
                methodArgs.setResultCode("3");
                methodArgs.setResultMessage("method长度小于4!");
                return methodArgs;
            }

            // 其他方式，解密data的编码
            if (base64Flag == 1) {
                args = Base64Method.decryptUrlSafeBase64(methodData);
            }

            serviceName = CallDataUtils.getServiceName(method);
            serviceSecondName = CallDataUtils.getSecondServiceName(method);
            methodName = CallDataUtils.getMethod(method);

            methodArgs.setResultCode("1");
            methodArgs.setResultMessage("成功过滤!");
            methodArgs.setMethodData(args);
            methodArgs.setMethodName(methodName);
            methodArgs.setServiceName(serviceName);
            methodArgs.setServiceSecondName(serviceSecondName);
            return methodArgs;
        } catch (Exception ex) {
            ex.printStackTrace();
            methodArgs.setResultCode("2");
            methodArgs.setResultMessage("CallDataFilter处理异常：" + ex.getMessage() + "!");
            return methodArgs;
        }
    }
}
